import 'package:flutter/material.dart';
import '../constants/app_theme.dart';
import '../constants/app_routes.dart';
import '../constants/app_strings.dart';
import '../providers/settings_provider.dart';
import 'package:provider/provider.dart';

/// 启动页面
/// 显示应用Logo、加载动画和初始化应用
class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen>
    with TickerProviderStateMixin {
  late AnimationController _logoController;
  late AnimationController _textController;
  late Animation<double> _logoAnimation;
  late Animation<double> _textAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _startSplashSequence();
  }

  @override
  void dispose() {
    _logoController.dispose();
    _textController.dispose();
    super.dispose();
  }

  /// 初始化动画控制器
  void _initializeAnimations() {
    // Logo动画控制器
    _logoController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );

    // 文字动画控制器
    _textController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );

    // Logo缩放动画
    _logoAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _logoController,
      curve: Curves.elasticOut,
    ));

    // 文字透明度动画
    _textAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _textController,
      curve: Curves.easeInOut,
    ));

    // 文字滑动动画
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.5),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _textController,
      curve: Curves.easeOutCubic,
    ));
  }

  /// 开始启动页动画序列
  void _startSplashSequence() async {
    // 延迟500ms后开始Logo动画
    await Future.delayed(const Duration(milliseconds: 500));
    _logoController.forward();

    // Logo动画完成后开始文字动画
    await Future.delayed(const Duration(milliseconds: 800));
    _textController.forward();

    // 等待所有动画完成后进行页面跳转
    await Future.delayed(const Duration(milliseconds: 1500));
    _navigateToNextScreen();
  }

  /// 导航到下一个页面
  void _navigateToNextScreen() async {
    if (!mounted) return;

    try {
      // 获取设置Provider
      final settingsProvider = context.read<SettingsProvider>();

      // 根据是否首次启动决定导航目标
      if (settingsProvider.isFirstLaunch) {
        AppRoutes.navigateAndClearStack(context, AppRoutes.onboarding);
      } else {
        AppRoutes.navigateAndClearStack(context, AppRoutes.main);
      }
    } catch (e) {
      debugPrint('导航失败: $e');
      // 发生错误时默认进入主页
      AppRoutes.navigateToHome(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          gradient: AppTheme.primaryGradient,
        ),
        child: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 顶部空间
              const Spacer(flex: 2),

              // Logo区域
              _buildLogoSection(),

              // 应用名称和标语
              _buildTextSection(),

              // 底部空间和加载指示器
              const Spacer(flex: 2),
              _buildLoadingSection(),

              // 底部间距
              const SizedBox(height: 48),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建Logo区域
  Widget _buildLogoSection() {
    return AnimatedBuilder(
      animation: _logoAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: _logoAnimation.value,
          child: Container(
            width: 120,
            height: 120,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(30),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 20,
                  offset: const Offset(0, 10),
                ),
              ],
            ),
            child: const Icon(
              Icons.cloud_outlined,
              size: 60,
              color: AppTheme.primaryColor,
            ),
          ),
        );
      },
    );
  }

  /// 构建文字区域
  Widget _buildTextSection() {
    return AnimatedBuilder(
      animation: _textAnimation,
      builder: (context, child) {
        return SlideTransition(
          position: _slideAnimation,
          child: FadeTransition(
            opacity: _textAnimation,
            child: Column(
              children: [
                const SizedBox(height: 32),
                
                // 应用名称
                Text(
                  AppStrings.zh('app_name'),
                  style: const TextStyle(
                    fontSize: 32,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                    letterSpacing: 1.2,
                  ),
                ),
                
                const SizedBox(height: 8),
                
                // 应用标语
                Text(
                  AppStrings.zh('app_slogan'),
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white.withOpacity(0.9),
                    fontWeight: FontWeight.w300,
                  ),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建加载区域
  Widget _buildLoadingSection() {
    return Column(
      children: [
        // 加载动画
        SizedBox(
          width: 40,
          height: 40,
          child: CircularProgressIndicator(
            strokeWidth: 3,
            valueColor: AlwaysStoppedAnimation<Color>(
              Colors.white.withOpacity(0.8),
            ),
          ),
        ),
        
        const SizedBox(height: 16),
        
        // 加载文字
        Text(
          AppStrings.zh('loading'),
          style: TextStyle(
            fontSize: 14,
            color: Colors.white.withOpacity(0.8),
            fontWeight: FontWeight.w300,
          ),
        ),
      ],
    );
  }
}